package com.ex.kotlin

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayout
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.ex.kotlin.ui.main.SectionsPagerAdapter

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = findViewById(R.id.view_pager)
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = findViewById(R.id.tabs)
        tabs.setupWithViewPager(viewPager)
        val fab: FloatingActionButton = findViewById(R.id.fab)

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }

        //todo java 写法
//        val editor: SharedPreferences.Editor = getPreferences(Context.MODE_PRIVATE).edit()
//        editor.putFloat("aaa", 10f)
//        editor.putBoolean("bbb", true)
//        editor.apply()

        //TODO kotlin 写法
        getPreferences(Context.MODE_PRIVATE).edit {
            putFloat("aaa", 10f)
            putBoolean("bbb", true)
        }

        //Todo kotlin 函数
        getPreferences(Context.MODE_PRIVATE).modify {
            putFloat("aaa", 10f)
            putBoolean("bbb", true)
        }

    }

    fun SharedPreferences.modify(block: SharedPreferences.Editor.() -> Unit) {
        val editor: SharedPreferences.Editor = edit()
        editor.block()
        editor.apply()
    }
}